import { createRouter, createWebHistory, type RouteRecordRaw, type Router } from 'vue-router'

//静态路由
const routes: Array<RouteRecordRaw> = [{
    path: '/',
    name: 'index',
    component: () => import('@/views/index.vue')
}, {
    path: '/about',
    name: 'about',
    component: () => import('@/views/about.vue')
}, {
    //404
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
}, 
{
    //从定向到404
    path: '/:pathMatch(.*)*',
    redirect: '/404'
}
]

//动态路由
const componentMap: Record<string, () => Promise<any>> = {
    dynamic: () => import('@/views/Dynamic.vue'),
    dynamic2: () => import('@/views/Dynamic2.vue'),
}

const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior: (_to, _from, savedPosition) => {
        console.log(savedPosition)
        if (savedPosition) {
            return savedPosition
        }
    }
})
function addRoutes(routes: Array<RouteRecordRaw>): void {
    routes.forEach(route => {
        router.addRoute(route)
    })
    const routesToStore = routes.map(route => ({
        path: route.path,
        name: route.name
    }))
    localStorage.setItem('dynamicRoutes', JSON.stringify(routesToStore))
}

function restoreRoutes(): void {
    const savedRoutes = localStorage.getItem('dynamicRoutes')
    if (savedRoutes) {
        const parsedRoutes = JSON.parse(savedRoutes) as Array<{ path: string; name: string }>
        parsedRoutes.forEach(route => {
            router.addRoute({
                ...route,
                component: componentMap[route.name],
            })
        })
        
    }
}


router.beforeEach(async (to, _from, next) => {
    console.log(to)
    if (!router.hasRoute(to.name as string)) {
        next({ path: to.fullPath, replace: true })
    } else {
        next()
    }
})

//模拟动态获取路由
function getRouters(){
    setTimeout(() => {
        const dynamicRoutes: Array<RouteRecordRaw> = [
        {
            path: '/dynamic',
            name: 'dynamic',
            component: () => import('@/views/Dynamic.vue')
        },
        {
            path: '/dynamic2',
            name: 'dynamic2',
            component: () => import('@/views/Dynamic2.vue')
        }
        ]
        addRoutes(dynamicRoutes)
    }, 1000)
}


// 初始化路由
function initRouter(): Router {
    restoreRoutes()
    getRouters()
    return router
}
export { initRouter, addRoutes }